<template>
  <ElCard>
    <div class="flex justify-start">
      <el-button class="mr-2" type="primary" @click="returnPage">返回</el-button>
    </div>
    <div class="production-scheduling">
      <el-form  class="flex flex-wrap justify-start" style="align-items: center;" label-width="100px">
        <el-form-item label="排产编号:">
          <el-input v-model="productionPlan.productionPlanCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="总计划数量:" >
          <el-input-number v-model="productionPlan.planQuantity" :min="0" disabled></el-input-number>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="productionPlan.remark" type="textarea" disabled :rows="1"/>
        </el-form-item>
      </el-form>

      <el-table :data="materialList" v-loading="loadingTable" border style="width: 100%; margin-top: 20px">
        <el-table-column prop="materialCode" label="物料编码" align="center" width="220"></el-table-column>
        <el-table-column prop="materialName" label="物料名称" align="center" width="220"></el-table-column>
        <el-table-column prop="orderQuantity" label="计划数量" align="center" width="100"></el-table-column>
        <el-table-column prop="schedulingQuantity" label="排产数量" align="center" width="100">
          <template #default="scope">
            {{scope.row.schedulingQuantity}}
          </template>
        </el-table-column>
        <el-table-column label="生产车间" width="160" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.workshop" placeholder="请选择车间" :disabled="true">
              <el-option
                v-for="(item, index) in gridList"
                :key="index"
                :label="item.gname"
                :value="item.gid"
              />
            </el-select>
          </template>
        </el-table-column>

        <!-- 动态生成日期列 -->
        <el-table-column
          v-for="(planTime, index) in formattedPlanTimes"
          :key="index"
          :prop="planTime"
          :label="planTime"
          width="160"
          align="center"
        >
          <template #default="scope">
            {{scope.row.quantities[planTime]}}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </ElCard>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import {
  ElCard,
  ElDatePicker,
  ElPagination,
  ElMessage,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  ElButton,
  ElFormItem,
  ElRadio,
  ElRadioGroup,
  ElOption,
  ElForm,
  ElDialog,
  ElSelect,
  ElRadioButton
} from "element-plus";
import { Button } from "ant-design-vue";
import { getGridApi, getProductionPlanDetailApi, updateProductionPlanApi } from "#/api/productionPlan/index.js";
import { useRoute, useRouter } from "vue-router";

// 排产类型（周/月）
const schedulingType = ref('week');
const planId = ref(null); // 计划ID
const loadingTable = ref(true)
// 物料列表
const materialList = ref([]);
const productionPlan = ref({});
// 返回事件
const returnPage = () => {
  router.push({name:"productionPlanList"}); // 返回列表页
};
const gridList = ref([]);
// 日期列（动态生成）
const formattedPlanTimes = ref([]); // 格式化后的计划时间列表
const router = useRouter();
const route = useRoute();

// 获取车间列表
const getGridList = async () => {
  await getGridApi().then((response) => {
    gridList.value = response.data.content;
  })
};

// 获取生产计划详情
const getProductionPlanDetail = () => {
  loadingTable.value = true;
  const id = route.params.id; // 从路由参数获取计划ID
  planId.value = id;
  getProductionPlanDetailApi({ id:id}).then(response => {
    productionPlan.value= response.data[0];
    const detailList = response.data[0].productPlanMaterialList || []; // 确保 detailList 是一个数组

    // 提取所有唯一的 planTime
    const planTimes = new Set();
    detailList.forEach(detail => {
      (detail?.productPlanMaterialNumberList || []).forEach(item => { // 确保 planMaterialNumberList 是一个数组
        planTimes.add(item.planTime);
      });
    });

    formattedPlanTimes.value = Array.from(planTimes).map(time => formatDate(new Date(time)));
    // 重组物料数据，包含每个 planTime 的 quantity
    materialList.value = detailList.map(detail => {
      const quantities = {};
      (detail.productPlanMaterialNumberList || []).forEach(item => { // 确保 planMaterialNumberList 是一个数组
        quantities[formatDate(new Date(item.planTime))] = item.quantity;
      });
      return {
        id: detail.id,
        materialCode: detail.materialCode,
        materialName: detail.materialName,
        orderQuantity: detail.orderQuantity,
        workshop: detail.gripId,
        schedulingQuantity: detail.schedulingQuantity,
        quantities // 每个 planTime 对应的 quantity
      };
    });
    loadingTable.value=false;
  }).catch(error => {
    loadingTable.value=false;
    console.error('获取生产计划详情失败:', error);
    ElMessage.error('获取生产计划详情失败');
  });
};

// 格式化日期为字符串
const formatDate = (date) => {
  return date ? `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}` : '';
};



// 格式化计划时间
const formatPlanTime = (dateString) => {
  const [year, month, day] = dateString.split('-');
  return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} 00:00:00`;
};


// 初始化
onMounted(() => {
  getGridList();
  getProductionPlanDetail();
});
</script>

<style scoped>
.production-scheduling {
  padding: 20px;
}

.quantity-input {
  margin-left: 10px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
}
</style>
